package com.service.scheduling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.dao.dto.MemberRank;
import com.service.dao.dto.OrderMemberRank;
import com.service.dao.enums.*;
import com.service.dao.mapper.OrderProductHrComboDetailsMapper;
import com.service.dao.mapper.OrderProductHrComboMapper;
import com.service.dao.model.Member;
import com.service.dao.model.OrderProductHrCombo;
import com.service.dao.model.OrderProductHrComboDetails;
import com.service.dao.model.ProductHrCombo;
import com.service.scheduling.dto.MemberStoreChange;
import com.service.scheduling.service.*;
import com.service.scheduling.support.MemberStoreLockUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Service("hashRateOrderService")
public class OrderProductHrComboServiceImpl extends ServiceImpl<OrderProductHrComboMapper, OrderProductHrCombo> implements OrderProductHrComboService {

    @Autowired
    private ConfigService configService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderProductHrComboDetailsMapper comboDetailsMapper;
    @Autowired
    private MemberJAService memberJAService;
    @Autowired
    private ProductHrComboService productHrComboService;
    @Autowired
    private MemberStoreLockUtils memberStoreLockUtils;
    @Autowired
    private MemberStoreService memberStoreService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder() {

        Date validDate = configService.getOrderOverdueTime();
        if (ObjectUtils.isEmpty(validDate)) {
            return;
        }
        log.info("cancelOrder 取消{}之前未支付订单 --- start",
                DateFormatUtils.format(validDate, "yyyy-MM-dd HH:mm:ss"));
//        List<OrderProductHrCombo> hrComboList = list(new QueryWrapper<OrderProductHrCombo>().lambda()
//                .eq(OrderProductHrCombo::getOrderStatus, HashRateOrderEnums.Status.not_pay.getCode())
//                .le(OrderProductHrCombo::getCreateTime, validDate));
        List<OrderProductHrCombo> hrComboList = baseMapper.listNotPayByTime(HashRateOrderEnums.Status.not_pay.getCode(),validDate);
        List<ProductHrCombo> cancelList = new ArrayList<>();
        List<OrderProductHrCombo> updateHrComboOrder = hrComboList.stream().map(item -> {
            //查询订单详情
            OrderProductHrComboDetails orderProductHrComboDetails = comboDetailsMapper.selectOne(new QueryWrapper<OrderProductHrComboDetails>().lambda()
                .eq(OrderProductHrComboDetails::getHrOrderId, item.getId()));
            //查询产品库存
            ProductHrCombo combo = productHrComboService.getById(orderProductHrComboDetails.getComboId());
            combo.setStock(combo.getStock()+item.getTotalComboNum());
            cancelList.add(combo);
            OrderProductHrCombo updateHrCombo = new OrderProductHrCombo();
            updateHrCombo.setId(item.getId());
            updateHrCombo.setOrderStatus(HashRateOrderEnums.Status.noneffective.getCode());
            return updateHrCombo;
        }).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(updateHrComboOrder)) {
            log.info("cancelOrder 取消{}之前未支付订单 数量 0 --- end",
                    DateFormatUtils.format(validDate, "yyyy-MM-dd HH:mm:ss"));
            return;
        }
        updateBatchById(updateHrComboOrder);
        //更新产品库存信息
        productHrComboService.updateBatchById(cancelList);
        log.info("cancelOrder 取消{}之前未支付订单 数量 {} --- end",
                DateFormatUtils.format(validDate, "yyyy-MM-dd HH:mm:ss"), updateHrComboOrder.size());

    }

    @Override
    public List<OrderProductHrCombo> listMiningOrder(Integer coinsId,Date startTime) {
        return baseMapper.listOrderByMemberStatus(coinsId,HashRateOrderEnums.getHrComboUsingStatus(), CommonStatusEnums.ACTIVE.getCode(),startTime);
    }

    @Override
    @Transactional
    public void updateHrComboRateOrder2Complete(List<Integer> orderIdList) {
        List<OrderProductHrCombo> updateHrComboOrder = orderIdList.stream().map(item -> {
            OrderProductHrCombo updateHrCombo = new OrderProductHrCombo();
            updateHrCombo.setId(item);
            updateHrCombo.setOrderStatus(HashRateOrderEnums.Status.complete.getCode());
            OrderProductHrCombo returnHrComboPledge = baseMapper.selectById(updateHrCombo.getId());
            OrderProductHrComboDetails details = comboDetailsMapper.selectOne(new QueryWrapper<OrderProductHrComboDetails>().lambda()
                .eq(OrderProductHrComboDetails::getHrOrderId, updateHrCombo.getId())
            );
            try{
                boolean isLock = memberStoreLockUtils.lock(returnHrComboPledge.getMemberId(), CoinsEnum.FIL.getCode());
                if (!isLock) {
                    return updateHrCombo;
                }
                if (details.getPledgeNum().compareTo(BigDecimal.ZERO) <= 0) {
                    return updateHrCombo;
                }
                memberStoreService.changeMemberStore(
                        MemberStoreChange.builder()
                                .memberId(returnHrComboPledge.getMemberId())
                                .coinsId(CoinsEnum.FIL.getCode())
                                .coinsName(CoinsEnum.FIL.getName())
                                .jaType(MemberJAType.PAY_HR_COMBO_PLEDGE_RETURN)
                                .orderId(returnHrComboPledge.getId())
                                .changeNum(details.getPledgeNum())
                                .remark(MemberJAType.PAY_HR_COMBO_PLEDGE_RETURN.getMsg())
                                .build());
            }finally {
                memberStoreLockUtils.unlock(returnHrComboPledge.getMemberId(), CoinsEnum.FIL.getCode());
            }
            return updateHrCombo;
        }).collect(Collectors.toList());

        if (ObjectUtils.isEmpty(updateHrComboOrder)) {
            return;
        }
        updateBatchById(updateHrComboOrder);
    }

    @Override
    @Transactional
    public void updateBZZHrComboRateOrder2Complete(List<Integer> orderIdList) {
        List<OrderProductHrCombo> updateHrComboOrder = orderIdList.stream().map(item -> {
            OrderProductHrCombo updateHrCombo = new OrderProductHrCombo();
            updateHrCombo.setId(item);
            updateHrCombo.setOrderStatus(HashRateOrderEnums.Status.complete.getCode());
            return updateHrCombo;
        }).collect(Collectors.toList());

        if (ObjectUtils.isEmpty(updateHrComboOrder)) {
            return;
        }
        updateBatchById(updateHrComboOrder);
    }

    @Override
    public OrderProductHrComboDetails getHrComboDetail(Integer orderId) {
        return comboDetailsMapper.selectOne(new QueryWrapper<OrderProductHrComboDetails>().lambda()
                .eq(OrderProductHrComboDetails::getHrOrderId, orderId));
    }

    /**
     * @param coinsName
     * @param currentMonth
     * @Description: 统计本月排行
     * @Author: ty
     * @Date: 2021/5/6 15:19
     * @param: [coinsName, currentMonth, limitNum]
     * @return: java.util.List<com.service.dao.dto.MemberRankRep>
     */
    @Override
    public List<MemberRank> totalRankByPayMoneyAndSomeMonth(String coinsName, Date currentMonth) {
        String currentMonthStr = DateFormatUtils.format(currentMonth, DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
        List<MemberRank> memberRankRepList = baseMapper.totalRankByPayMoneyAndSomeMonth(coinsName, currentMonthStr, 8);
        if(!ObjectUtils.isEmpty(memberRankRepList)){
            memberRankRepList.parallelStream().forEach(item->{
                List<Member> inviteMembers = memberService.listByPid(item.getId());
                if(!ObjectUtils.isEmpty(inviteMembers)){
                    item.setInviteMemberNum(inviteMembers.size());
                }else{
                    item.setInviteMemberNum(0);
                }
            });
        }
        return memberRankRepList;
    }

    /**
     * @Description: 统计全网有效算力总量
     * @Author: ty
     * @Date: 2021/5/8 14:24
     * @param: []
     * @return: java.math.BigDecimal
     **/
    @Override
    public BigDecimal totalAllPlatformHashRate() {
        return baseMapper.totalAllEffectiveOrderPay(HashRateOrderEnums.getHrComboUsingStatus());
    }

    /**
     * @param memberIds
     * @param orderStatus
     * @Description: 统计用户列表的有效算力T数
     * @Author: ty
     * @Date: 2021/5/8 16:02
     * @param: [memberIds, orderStatus]
     * @return: java.math.BigDecimal
     */
    @Override
    public BigDecimal totalEffectiveHashRateByMemberIdsAndStatus(List<Integer> memberIds, List<Integer> orderStatus, String currentMonth) {
        return baseMapper.totalEffectiveHashRateByMemberIdsAndStatus(memberIds, orderStatus,currentMonth);
    }
}
